package com.ss.android.caijing.stepcounterlib.log;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.ss.android.caijing.stepcounterlib.utils.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * Created by zdh on 2017/11/10.
 */

public class CodeLog {
    private static final String TAG = CodeLog.class.getName();

    public static boolean InitLogConfig(Context context) {
        return LogWriter.instance().initLogFile(context);
    }

    public static void i(String tag, String msg) {
        String logContent = "info : " + tag + " -- " + msg;
        LogWriter.instance().writeLog(logContent);
    }

    public static void e(String tag, String msg) {
        String logContent = "error : " + tag + " -- " + msg;
        LogWriter.instance().writeLog(logContent);
    }

    public static String getAllLog() {
        return LogWriter.instance().readAllLog();
    }

    public static boolean clearLog() {
        return LogWriter.instance().clearLog();
    }

    private static class LogWriter {
        private String LOG_NAME = "/steplog.txt";
        private String DIR_LOG = "/logs";
        private String SUFFIX = ".log";
        private String encoding = "GBK"; // 字符编码(可解决中文乱码问题 )
        private String mLogPath = "";

        private volatile static LogWriter logWriter = null;

        private static LogWriter instance() {
            if (logWriter == null) {
                synchronized (LogWriter.class) {
                    if (logWriter == null) {
                        logWriter = new LogWriter();
                    }
                }
            }
            return logWriter;
        }

        private LogWriter() {
        }

        boolean initLogFile(Context context) {
            mLogPath = getLogPath(context) + LOG_NAME;
            try {
                File logFile = new File(mLogPath);
                if (logFile.exists() && logFile.isFile()) {
                    InputStreamReader read = new InputStreamReader(
                            new FileInputStream(logFile), encoding);
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String firstLine = bufferedReader.readLine();
                    read.close();
                    if (firstLine.equals(String.valueOf(Util.getTodayTime()))) {
                        return true;
                    } else {
                        logFile.delete();
                        boolean isSuccess = logFile.createNewFile();
                        writeLog(Util.getTodayTime());
                        return isSuccess;
                    }
                } else {
                    boolean isSuccess = logFile.createNewFile();
                    writeLog(Util.getTodayTime());
                    return isSuccess;
                }
            } catch (Exception ex) {
                SSLog.e(TAG, ex.toString());
            }
            return false;
        }

        synchronized void writeLog(Object value) {
            try {
                File logFile = new File(mLogPath);
                if (!logFile.exists()) return;
                Writer writer = new OutputStreamWriter(new FileOutputStream(logFile, true), encoding);
                writer.append(value.toString()).append("\n");
                writer.flush();
                writer.close();
            } catch (Exception ex) {
                SSLog.e(TAG, ex.toString());
            }
        }

        private String readAllLog() {
            String content = "";
            try {
                File logFile = new File(mLogPath);
                if (logFile.exists() && logFile.isFile()) {
                    InputStreamReader read = new InputStreamReader(
                            new FileInputStream(logFile), encoding);
                    BufferedReader bufferedReader = new BufferedReader(read);
                    StringBuilder contentBuilder = new StringBuilder();
                    String temLine = "";
                    while ((temLine = bufferedReader.readLine()) != null) {
                        contentBuilder.append(temLine).append("\n");
                    }
                    content = contentBuilder.toString();
                }
            } catch (Exception ignored) {

            }
            return content;
        }

        private boolean clearLog() {
            try {
                File logFile = new File(mLogPath);
                if (logFile.exists() && logFile.isFile()) {
                    if (logFile.delete()) {
                        boolean isSuccess = logFile.createNewFile();
                        writeLog(Util.getTodayTime());
                        return isSuccess;
                    }
                }
            } catch (Exception ignored) {

            }
            return false;
        }

        private String getLogPath(Context context) {
            final String LOG_CACHE_DIR = context.getFilesDir().getAbsolutePath() + DIR_LOG + "/";
            final String sdDir = getSDPath();
            final String saveDir = (TextUtils.isEmpty(LOG_CACHE_DIR)) ? sdDir : LOG_CACHE_DIR
                    + SUFFIX;
            if (!doesExisted(saveDir)) {
                assert saveDir != null;
                new File(saveDir).mkdirs();
            }
            return saveDir;
        }

        private boolean doesExisted(String filePath) {
            if (filePath == null || filePath.isEmpty()) {
                return false;
            } else {
                File logFile = new File(filePath);
                return logFile.exists();
            }
        }

        private String getSDPath() {
            File sdDir = null;
            boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
            if (sdCardExist) {
                sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            }
            if (sdDir != null)
                return sdDir.toString();
            else
                return null;

        }
    }
}
